<html>
<div id="content_div">
      <form>
              <div id="miDiv">
                  <input type="button" name="fname" onclick="javascript:updateFriends()" />Update Friends<br />
              </div>
      </form>
     
  </div>
  <script type="text/javascript">

    var html;
    var arrayIdAmigos = new Array();
    var cont = 0;
    var idUserPrincipal = 0;
    
    function pause(milliseconds) {
        var dt = new Date();
        while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
    }
    
    function makeCachedRequest(url, callback, params, refreshInterval) {
      var ts = new Date().getTime();
      var sep = "?";
      if (refreshInterval && refreshInterval > 0) {
        ts = Math.floor(ts / (refreshInterval * 1000));
      }
      if (url.indexOf("?") > -1) {
        sep = "&";
      }
      url = [ url, sep, "nocache=", ts ].join("");
      alert('url desde makeCachedRequest: '+url);
      gadgets.io.makeRequest(url, callback, params);
    }


    function servicioSeleccionado(){
   
        var radio = document.getElementsByName('service');
        var valorSeleccionado;
       
        for(i=0; i <radio.length; i++){
                if(radio[i].checked){
                    valorSeleccionado = radio[i].value;
                }
            }
        return valorSeleccionado;
    }

    function holaMundo(){
        /*
        var radio = document.getElementsByName('service');
        var valorSeleccionado;
       
        for(i=0; i <radio.length; i++){
                if(radio[i].checked){
                    valorSeleccionado = radio[i].value;
                }
            }
            
        var friends = document.getElementsByName('friend');
        var arraySelectedFriends = new Array();
        cont = 0;
       
        for(j=0; j <friends.length; j++){
                
                if(friends[j].checked){
                    arraySelectedFriends[cont] = friends[j].value;
                    cont++;
                }
        }
        
        
            
        */
           
        alert('Servicio: '+servicioSeleccionado());
       
    }
    
    function clearFriends(){
    
        var checkboxFriends = document.getElementsByName('friends');
        for(i=0; i <checkboxFriends.length; i++){
                checkboxFriends[i].checked = false;
        }
        
    }
    
    function selectedService(){
    
        var radio = document.getElementsByName('service');
        var valorSeleccionado;
       
        for(i=0; i <radio.length; i++){
                if(radio[i].checked){
                    valorSeleccionado = radio[i].value;
                }
            }
        return valorSeleccionado;
        
    }
    
    function updateFriends(){
    
        var updatedService = selectedService();
        var selectedFriends = new Array();
        
        var checkboxFriends = document.getElementsByName('friends');
        
        for(i=0; i <checkboxFriends.length; i++){
            
            if(checkboxFriends[i].checked == true){
                selectedFriends.push(checkboxFriends[i].value);
            }
        }
        
        if(selectedFriends.length > 0){
        
            var putData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><uservice><id>"+updatedService+"</id><users>";
            for(j=0; j <selectedFriends.length; j++){
                putData += "<Item><id>"+selectedFriends[j]+"</id></Item>";
            }
            putData += "</users></uservice>";
            var url = "http://194.224.200.125:8080/REST_CXF/rest/service/"+updatedService;
            
            var params = {};
            
            //alert('putData antes: '+putData);
            //putData = gadgets.io.encodeValues(putData);
            //alert('putData despues: '+putData);
            
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.PUT;
            params[gadgets.io.RequestParameters.POST_DATA]= putData;
            params[gadgets.io.RequestParameters.HEADERS] = {"Accept":"application/xml","Content-Type":"application/xml"};
            gadgets.io.makeRequest(url, responseUpdateFriends, params); 
        }
        
    }
    
    function responseUpdateFriends(obj){
        alert('respuesta update');
    }
   
    function refreshServiceInfo(){
        
        var valorSeleccionado = selectedService();
        
        clearFriends();
        
        var params = {};  
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;  
        var url = "http://194.224.200.125:8080/REST_CXF/rest/service/"+valorSeleccionado;
        
        //gadgets.io.makeRequest(url, responseChangeService, params);
        makeCachedRequest(url, responseChangeService, params, 0); 
        
        //alert('Nuevo valor seleccionado: '+servicioSeleccionado());
       
    }
   

    function getContacts() {
    var params = {};  
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;  
    var url = "http://194.224.200.125:8080/REST_CXF/rest/user/"+idUserPrincipal;
    gadgets.io.makeRequest(url, response, params);
   
  };
  
  function getServices() {
    var params = {};  
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;  
    var url = "http://194.224.200.125:8080/REST_CXF/rest/service";
    gadgets.io.makeRequest(url, responseService, params);
   
  };
  
  function responseChangeService(obj) {

        var selectedFriends = new Array();
        var domdataServices = obj.data;
        var usersListElements = domdataServices.getElementsByTagName("users");
        var usersList = usersListElements.item(0);
        var itemList = usersList.childNodes;
        if(itemList.length > 0){
        
             for (var i = 0; i < itemList.length ; i++) {
                 
                var node = itemList.item(i);
                var idFriend = node.firstChild.firstChild.nodeValue;
                selectedFriends.push(idFriend);
             }
             
            var checkboxFriends = document.getElementsByName('friends');
            for(j=0; j <checkboxFriends.length; j++){
                var valueIdFriend = checkboxFriends[j].value;
                for(k=0; k <selectedFriends.length; k++){
                
                    if(valueIdFriend == selectedFriends[k]){
                        checkboxFriends[j].checked = true;
                    }
                }
                
            }
        }
        
    }
  
  function responseService(obj) {

    var domdataServices = obj.data;
    var servicesList = domdataServices.getElementsByTagName("uservice");
    
    //alert('longitud lista servicios: '+servicesList.length);
    
    for (var i = 0; i < servicesList.length ; i++) {
    
        var idCreator;
        var servName;
        var servId;
        var servicio = servicesList.item(i);
        var nodeList = servicio.childNodes;
        for (var j = 0; j < nodeList.length ; j++) {
        
            var node = nodeList.item(j);
            if (node.nodeName == "creator"){
                
                idCreator = node.firstChild.firstChild.nodeValue;
                
            
            }
            if (node.nodeName == "name"){
                
                servName = node.firstChild.nodeValue;
            
            }
            if (node.nodeName == "id"){
                
                servId = node.firstChild.nodeValue;
            
            }
        }
        if(idCreator == idUserPrincipal){
            
        
            //html += "Servicio: Name: "+servName+", Id: "+servId+"</br>";
            html += "<input type=\"radio\" name=\"service\" value=\""+servId+"\" onchange=\"refreshServiceInfo()\" />"+servName+"</br>";
        }
    }
    
    html += "</div>";
        // Output html in div.
        document.getElementById('miDiv').innerHTML += html;
  }
  
  
  function responseFriend(obj) {          
     
     var domdataFriend = obj.data;  
     var userList = domdataFriend.getElementsByTagName("user");
     var itemUser = userList.item(0);
     var nodeList = itemUser.childNodes;
     
     for (var j = 0; j < nodeList.length ; j++) {
         
                 var node = nodeList.item(j);
                 var firstName = "nombre por defecto";
                if (node.nodeName == "firstName")
                {       
                    //html += "entro if firstName"+"</br>";
                    firstName = node.firstChild.nodeValue;
                    
                    html += "<input type=\"checkbox\" name=\"friends\" value=\""+arrayIdAmigos[cont]+"\" />"+firstName+"<br />";
                    
                    //html += "nombre de Amigo: "+firstName+"</br>";
                    //alert('dentro if');
                    
                }
    }
    
    cont++;
    if(cont < arrayIdAmigos.length){
        
        var paramsFriendBucle = {};  
        paramsFriendBucle[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM; 
        var urlFriendBucle = "http://194.224.200.125:8080/REST_CXF/rest/user/"+arrayIdAmigos[cont];
        gadgets.io.makeRequest(urlFriendBucle, responseFriend, paramsFriendBucle);
        
    }else{
    
         html += "<br/><br/>";
         getServices();
         
    }
     
}
  
  // Callback function to process the response
  function response(obj) {    
      var paramsFriend = {};  
      paramsFriend[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;  
     var domdata = obj.data;  
    //var responseText = obj.text;  
    // Set CSS for div.
    html = "<div style='padding: 5px;background-color: #FFFFBF;font-family:Arial, Helvetica;"
    + "text-align:left;font-size:90%'>";
 
     html += "Amigos del usuario:"+"</br>";

    var itemList = domdata.getElementsByTagName("friends");
    
    var nodeFriends = itemList.item(0);
    
    var listaItems = nodeFriends.childNodes;
    
    for (var i = 0; i < listaItems.length ; i++) {
    
        var item = listaItems.item(i);
        listaId = item.childNodes;
        var idNodo = listaId.item(0);
        var valorId = idNodo.firstChild.nodeValue;
        
        //html += "valor: "+valorId+"</br>";
        
        //var urlFriend = "http://194.224.200.125:8080/REST_CXF/rest/user/"+valorId;
        //gadgets.io.makeRequest(urlFriend, responseFriend, paramsFriend);
        arrayIdAmigos[i] = valorId;
    }
    
    if(arrayIdAmigos.length > 0){
    
        var urlFriend = "http://194.224.200.125:8080/REST_CXF/rest/user/"+arrayIdAmigos[cont];
        gadgets.io.makeRequest(urlFriend, responseFriend, paramsFriend);
    }
    
   
  }
 
  
  gadgets.util.registerOnLoadHandler(getContacts);

 </script>
</html>